import React, { PureComponent } from 'react'
// import React, { Component, PureComponent } from 'react'

// export default class Child extends Component {
export default class Child extends PureComponent {
  state = {
    color: '',
    // 定义了一个冗余的state
    preColor: ''
    // color: this.props.color // 初始化一次
  }

  // 根据props 生成一个新的state
  static getDerivedStateFromProps(nextProps, prevState) {
    console.log(nextProps.color)
    console.log('child getDerivedStateFromProps')
    // 自己改也触发
    console.log(nextProps.color, prevState.color, 'nextProps.color prevState.color')
    if(nextProps.color === prevState.preColor){
      return null
    } else {
      return { // shallow merge state (浅复制)
        color: nextProps.color,
        preColor: nextProps.color
      }
    }
  }

  componentDidMount() {
    // console.log('child did mount')
    setTimeout(() => {
      this.setState({
        color: 'blue'
      }) 
     }, 3000)
  }
  // updating UNSAFE_即将废弃
  // componentWillReceiveProps(nextProps) {
  //   // console.log(nextProps)
  //   console.log('child componentWillReceiveProps')
  // }
  // PureComponent 都是优化用的，互斥的
  // showComponentUpdate(nextProps, nextState) {
  //   console.log('showComponentUpdate', nextProps, nextState)
  //   // return false
  //   return !(this.props.title === nextProps.title)
  // }
  // componentWillUpdate() {
  //   console.log('child componentWillUpdate')
  // }

  render() {
    // console.log('child render')
    return (
      <div>
        child color: {this.state.color}
      </div>
    )
  }
  // componentDidUpdate 与 getSnapshotBeforeUpdate 一起用
  getSnapshotBeforeUpdate() {
    // dom操作 上一次dom状态
    console.log('child getSnapshotBeforeUpdate')
    return 120
  }
  componentDidUpdate(prevProps, prevState, snapshot) {
    // console.log('child componentDidUpdate')
    console.log(snapshot)
  }

  componentWillUnmount() {
    // console.log('child componentWillUnmount')
  }
}
